/*
 * @Author: fuzhuang
 * @Date: 2023-12-11 09:23:21
 * @LastEditTime: 2025-05-01 15:27:39
 * @LastEditors: wangjun haodreams@163.com
 * @Description:
 * @FilePath: \golib\serialer\test\test.go
 */
package main

import (
	"flag"
	"fmt"
	"log"
	"strings"

	"gitee.com/haodreams/serial"
)

var paddr = flag.String("addr", "/com7,N,8,1", "串口地址")

// var paddr = flag.String("addr", "/dev/ttyO2,9600,N,8,1", "串口地址")
var phex = flag.Bool("hex", false, "是否16进制输入")
var pdata = flag.String("data", "", "要发送的数据")

func main() {
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	flag.Parse()
	if *paddr == "" {
		log.Fatalln("addr is empty")
	}

	com := serial.NewSerial(serial.WithConnect(*paddr), serial.WithTimeout(2000))
	err := com.Open()
	if err != nil {
		log.Fatalln(err)
	}

	data := strings.TrimSpace(*pdata)
	if data != "" {
		if *phex {
			data := strings.ReplaceAll(*pdata, " ", "")
			_, err := com.Write([]byte(data))
			if err != nil {
				log.Fatalln(err)
			}
		} else {
			*pdata = strings.ReplaceAll(*pdata, "\\n", "\n")
			*pdata = strings.ReplaceAll(*pdata, "\\r", "\r")
			fmt.Print(*pdata)
			com.Write([]byte(*pdata))
		}
	}
	bs := make([]byte, 1024)
	for {
		n, err := com.Read(bs)
		if err != nil {
			log.Println(err)
			if strings.Contains(err.Error(), "timeout") {
				continue
			}
			return
		}
		if n > 0 {
			if *phex {
				fmt.Printf("% 02x", bs[:n])
			} else {
				fmt.Print(string(bs[:n]))
			}
		}
	}
}
